package com.cloud.job.project.task;

import com.cloud.common.core.cons.CloudCons;
import com.cloud.common.core.utils.file.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;

/**
 * 定时清理日志
 * 只清除上个月的日志info error
 * 建议每个月20号2点整 清除上个月日志
 * cron(0 0 2 20 * ?)
 * INSERT INTO `sys_quartz_job` (`job_id`, `job_name`, `job_group`, `invoke_target`, `cron_expression`, `misfire_policy`, `concurrent`, `status`, `create_time`, `update_time`, `remark`)
 * VALUES (4, '定时清理日志', 'DEFAULT', 'clearLogTask.doClear', '0 0 2 20 * ?', '3', '1', 1, '2021-03-15 09:22:25', '2021-03-15 09:51:35', '定时清理日志');
 *
 * @author yan
 */
@Slf4j
@Component("clearLogTask")
public class ClearLogTask {

    /**
     * 需要删除日志的模块名
     */
    private final List<String> logList = Arrays.asList(CloudCons.SYSTEM, CloudCons.JOB, CloudCons.GATEWAY);

    /**
     * main方法 配置invoke_target => clearLogTask.doClear
     */
    public void doClear() {
        log.info(">>>>start clear log<<<<");
        String logPath = System.getProperty("user.dir") + "/logs";
        for (String module : logList) {
            String modulePath = logPath + "/" + module;
            List<File> fileList = FileUtils.getFiles(modulePath, ".gz");
            for (File file : fileList) {
                //info.log.2021-03-05.gz / info.log.2021-03-05-1.gz
                String name = file.getName().replace(".gz", "");
                //2021-03-05 10位
                String substring = name.substring(name.lastIndexOf(".") + 1);
                if (substring.length() < 10) {
                    continue;
                }
                //有些会出现 2021-03-05-1 因为设置了-%i
                String sub = substring.substring(0, 10);
                LocalDate date = LocalDate.parse(sub);
                if (LocalDate.now().getMonthValue() > date.getMonthValue()) {
                    boolean res = FileUtils.deleteFile(file.getAbsolutePath());
                    log.info("delete log module:{}, name:{}, date: {} ,result: {}", module, file.getName(), date, res);
                }
            }
        }
        log.info(">>>>end clear log<<<<");
    }

}
